﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class MenuListPage : Page, INavigableView<MenuListViewModel>
    {
        public MenuListViewModel ViewModel { get; }

        public MenuListPage(MenuListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.Execute(null);
            ViewModel.PageDto.SystemType_ID = App.ViewModel.SystemType;
        }

        [RelayCommand]
        private async Task Add()
        {
            await Edit(null);
        }

        [RelayCommand]
        private async Task EditById(string id)
        {
            if (!id.IsNullOrEmpty())
            {
                MenuEditPage page = App.GetService<MenuEditPage>();
                MenuEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IMenuService>.Instance.GetAsync(id);
                await page.ViewModel.InitData(id);
                page.ViewModel.IsEdit = true;
                page.ShowDialog();
                MenuEditViewModel viewModel2 = page.ViewModel;
                if (viewModel2 != null && viewModel2.Result?.Success == true)
                {
                    await ViewModel.GetData();
                }
            }
        }

        [RelayCommand]
        private async Task Edit(MenuInfo info)
        {
            MenuEditPage page = App.GetService<MenuEditPage>();
            if (info != null)
            {
                MenuEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IMenuService>.Instance.GetAsync(info.Id);
                await page.ViewModel.InitData(info.Id);
                page.ViewModel.IsEdit = true;
            }
            else
            {
                long num = 0L;
                if (!ViewModel.PageDto.PID.IsNullOrEmpty())
                {
                    num = await BLLFactory<IMenuService>.Instance.CountAsync((MenuInfo s) => s.PID == ViewModel.PageDto.PID);
                }
                string wpfType = GetType().Namespace + ".*";
                page.ViewModel.Item = new MenuInfo
                {
                    PID = ViewModel.PageDto.PID,
                    SystemType_ID = App.ViewModel.SystemType,
                    Creator = App.ViewModel.UserInfo.FullName,
                    WpfType = wpfType,
                    Seq = (num + 1).ToString("D3")
                };
                page.ViewModel.IsEdit = false;
            }
            page.ShowDialog();
           
            if (page.ViewModel.Result?.Success == true)
            {
                await ViewModel.GetTreeCommand.ExecuteAsync(null);
                await ViewModel.GetData();
            }
        }

        [RelayCommand]
        private async Task Delete(MenuInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.PageDto.PID = null;
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<MenuInfo> list = new List<MenuInfo>();
                foreach (MenuInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var importPage = App.GetService<ImportExcelPage>();
            importPage.ViewModel.Items?.Clear();
            importPage.ViewModel.TemplateFile = "功能菜单-模板.xls";
            importPage.OnDataSave -= ExcelData_OnDataSave;
            importPage.OnDataSave += ExcelData_OnDataSave;
            ViewModel.Navigate(typeof(ImportExcelPage));
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            DateTime dateTime = Convert.ToDateTime("1900-01-01");
            MenuInfo menuInfo = new MenuInfo();
            menuInfo.PID = GetRowData(dr, "父ID");
            menuInfo.Name = GetRowData(dr, "显示名称");
            menuInfo.Icon = GetRowData(dr, "图标");
            menuInfo.Seq = GetRowData(dr, "排序");
            menuInfo.FunctionId = GetRowData(dr, "功能ID");
            menuInfo.Visible = GetRowData(dr, "是否可见").ToInt32();
            menuInfo.Expand = GetRowData(dr, "是否展开").ToInt32();
            menuInfo.SystemType_ID = GetRowData(dr, "系统编号");
            menuInfo.Tag = GetRowData(dr, "特殊标签");
            menuInfo.WpfType = GetRowData(dr, "WPF窗体类型");
            menuInfo.Creator = GetRowData(dr, "创建人");
            menuInfo.Creator_ID = GetRowData(dr, "创建人ID");
            string rowData = GetRowData(dr, "创建时间");
            DateTime result;
            if (!string.IsNullOrEmpty(rowData))
            {
                if (DateTime.TryParse(rowData, out result) && result > dateTime)
                {
                    menuInfo.CreateTime = result;
                }
            }
            else
            {
                menuInfo.CreateTime = DateTime.Now;
            }
            menuInfo.Editor = GetRowData(dr, "编辑人");
            menuInfo.Editor_ID = GetRowData(dr, "编辑人ID");
            string rowData2 = GetRowData(dr, "编辑时间");
            if (!string.IsNullOrEmpty(rowData2))
            {
                if (DateTime.TryParse(rowData2, out result) && result > dateTime)
                {
                    menuInfo.EditTime = result;
                }
            }
            else
            {
                menuInfo.EditTime = DateTime.Now;
            }
            return await BLLFactory<IMenuService>.Instance.InsertAsync(menuInfo);
        }

        private async void menu_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is CustomTreeNode customTreeNode)
            {
                ViewModel.MenuTreeModel.SelectNode = customTreeNode;
                ViewModel.PageDto.PID = customTreeNode.Id;
                await ViewModel.GetData();
            }
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.MenuTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.MenuTreeModel.FilteredTreeItems = ViewModel.MenuTreeModel.TreeItems;
                return;
            }
            ViewModel.MenuTreeModel.FilteredTreeItems = ViewModel.MenuTreeModel.TreeItems.FindCustomNodes((CustomTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }

        private async void menu_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (menuTree.SelectedItem is CustomTreeNode customTreeNode)
            {
                MenuInfo menuInfo = await BLLFactory<IMenuService>.Instance.GetAsync(customTreeNode.Id);
                if (menuInfo != null)
                {
                    await Edit(menuInfo);
                }
            }
        }
    }
}
